# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.newforms import form_for_model

from django.conf import settings
from cat.models import *
#for pagination
from django.core.paginator import QuerySetPaginator as Paginator
from django.core.paginator import InvalidPage

import logging

def home(request, model="b",objectId="0",page_num=1, template='home.html'):
    #create the dict to pass back
    info_dict = {
        'site_name' : 'Digi-Cat',
        'user' : request.user
                }

    paginate_by = settings.PAGINATE_BY
    #what we get as parameter is always a string
    page_num = int(page_num)

    if model == 'b': #filter for books
        info_list = Paginator(Book.objects.all(),paginate_by)

    if model == 'a': #filter for author
        if objectId<>"0":
            info_list = Paginator(Book.objects.all().filter(authors__pk=int(objectId)),paginate_by)
            info_dict['author']= Author.objects.get(pk=int(objectId))
        else:
            info_list = Paginator(Author.objects.all(),paginate_by)

    if model == 'c': #filter for category
        if objectId<>"0":
            info_list = Paginator(Book.objects.all().filter(categories__pk=int(objectId)),paginate_by)
            info_dict['category']= Category.objects.get(pk=int(objectId))
        else:
            info_list = Paginator(Author.objects.all(),paginate_by)

    #if the user altered the URL for a particular page that doesn't exist
    try:
        page_info = info_list.page(page_num)
    except InvalidPage:
        page_num = 1
        page_info = info_list.page(page_num)

    has_previous = page_info.has_previous()
    has_next = page_info.has_next()
    #don't know how to concatenate dicts; is this the only way?
    info_dict['query_list']    = page_info.object_list
    info_dict['has_previous']  = has_previous
    info_dict['has_next']      = has_next
    info_dict['previous_page'] = page_num - 1
    info_dict['next_page']     = page_num + 1

    return render_to_response(template, info_dict)

def display_book_form(request, template="add_book.html"):
    info_dict = {
        'site_name'     : 'Digi-Cat',
        'user'          : request.user,
                }
    form = AddBookForm()
    info_dict['bookForm'] = form
    return render_to_response(template, info_dict)

def addbook(request):
    if request.method == 'POST':
        newbook = AddBookForm(request.POST)
        newbook.save()
    return HttpResponseRedirect('/')

#getting individual book details is separate coz there is no need for pagination
def book_home(request, objectId="0", template="book_home.html"):
    #create the dict to pass back
    info_dict = {
        'site_name'     : 'Digi-Cat',
        'user'          : request.user,
        'query_list'    : Book.objects.get(pk=int(objectId))
                }
    form = AddBookForm()
    info_dict['form'] = form
    return render_to_response(template, info_dict)

#view called by flexigrid to populate the grid
#ref: http://www.webplicity.net/flexigrid/
#ref: http://www.nickfessel.com/
#ref: http://docs.turbogears.org/2.0/RoughDocs/ToscaWidgets/Cookbook/FlexiGrid
#though flexigrid accepts json, it expects in a certain format
def populategrid(request):
    logging.debug("post details: " + str(request.POST))
    #page that is requested
    if request.POST.has_key('page'):
        pagenum = int(request.POST['page'])
    else:
        pagenum = 1
    #rows per page
    if request.POST.has_key('rp'):
        rp = int(request.POST['rp'])
    else:
        rp = 10
        
    if request.POST.has_key('sortname'):
        sortname = request.POST['sortname']
    else:
        sortname = 'title'
    
    if request.POST.has_key('sortorder'):
        sortorder = request.POST['sortorder']        
    else:
        sortorder = "desc"
    
    books = Book.objects.all()
    
    if request.POST.has_key('query'):
        #ref http://groups.google.com/group/django-users/browse_thread/thread/517c774723b76e5f/449c0089f51fc8b0#449c0089f51fc8b0
        query = str(request.POST['query'])
        qfld = str(request.POST['qtype'])
        if (query):
            if (qfld== 'authors'):
                qfld = 'authors__name'
                qfilter= {'%s__contains' % qfld : query}
            else:
                qfilter= {'%s__contains' % qfld : query}
            books = Book.objects.filter(**qfilter)
    count = books.count()
    
    start = int((pagenum - 1)* rp)
    books = books.order_by(sortname)[start:start+rp]        
    
    if sortorder == "desc":
        books = books.reverse()
        
    rows = [{'id': book.id,
             'cell': [book.title, ' & '.join([auth.name for auth in book.authors.all()]), book.publisher, book.isbn]} for book in books]
    
    from django.utils import simplejson
    data = simplejson.dumps(dict(page=pagenum, total = count, rows=rows))    
    logging.debug("pagenum: " + str(pagenum) + " rp: " + str(rp) + " start: " + str(start) + " count: " + str(count))
    
    return HttpResponse(data, mimetype='application/javascript')

def help(request):
    return render_to_response('help.html')